package com.flyxiaozhu.erp.admin.controllers;

import com.flyxiaozhu.erp.core.entities.GoodsTag;
import com.flyxiaozhu.erp.core.helper.DateHelper;
import com.flyxiaozhu.erp.core.libs.ErrorCode;
import com.flyxiaozhu.erp.core.libs.JSONResult;
import com.flyxiaozhu.erp.core.repositories.GoodsTagRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class GoodsTagController {
    @Autowired
    GoodsTagRepository goodsTagRepository;
    @Autowired
    com.flyxiaozhu.erp.core.services.GoodsTagService GoodsTagService;

    @Secured("ROLE_GOODS_TAGS_SELECT")
    @RequestMapping(value = "/goodsTag/select")
    public JSONResult getList() {
        List<GoodsTag> goodsTagList = goodsTagRepository.findAll();

        return new JSONResult().put("list", goodsTagList).put("total", goodsTagList.size());
    }

    @Secured("ROLE_GOODS_TAGS_INSERT")
    @RequestMapping(value = "/goodsTag/insert")
    public JSONResult add(GoodsTag goodsTag) {

        GoodsTag result = goodsTagRepository.findByTitle(goodsTag.getTitle());

        if (result != null) {
            return new JSONResult(ErrorCode.DUPLICATE_KEY, "标签名重复");
        }

        goodsTagRepository.save(goodsTag);

        return new JSONResult().put("model", goodsTag);
    }

    @Secured("ROLE_GOODS_TAGS_UPDATE")
    @RequestMapping(value = "/goodsTag/update")
    public JSONResult update(GoodsTag goodsTag) {
        GoodsTag old = GoodsTagService.findById(goodsTag.getId());
        if (old == null) {
            return new JSONResult(ErrorCode.NO_DATA, "标签ID错误");
        }

        GoodsTag result = goodsTagRepository.findByTitle(goodsTag.getTitle());

        if (result != null && result.getId() != goodsTag.getId()) {
            return new JSONResult(ErrorCode.DUPLICATE_KEY, "标签名重复");
        }


        BeanUtils.copyProperties(goodsTag, old);

        goodsTag.setUpdateTime(DateHelper.getStringDate());
        goodsTagRepository.save(goodsTag);

        return new JSONResult().put("count", 1).put("model", old);
    }

//    @Secured("ROLE_GOODS_TAGS_DELETE")
//    @RequestMapping(value = "/goodsTag/delete")
//    public JSONResult delete(@RequestParam String keys) {
//        List<Long> ids = CollectionUtils.map(keys.split(","), o -> Long.parseLong(o));
//
//        List<GoodsTag> goodsCategoryList = goodsTagRepository.findByIdIn(ids);
//        if (goodsCategoryList.size() != ids.size()) {
//            return new JSONResult(ErrorCode.NO_DATA, "标签id错误");
//        }
//
//        GoodsTagService.delete(goodsCategoryList);
//        return new JSONResult().put("count", 1).put("model", goodsCategoryList);
//    }
}
